//
//  HPSyncService.m
//  LockTest
//
//  Created by ZhangBo on 2018/12/2.
//  Copyright © 2018 ZhangBo. All rights reserved.
//

#import "HPSyncService.h"
#import "HPUser.h"

@interface HPSyncService ()
@property(nonatomic, strong) NSMutableDictionary *user;
@end

@implementation HPSyncService

- (instancetype)init {
    if (self = [super init]) {

        NSString *itemId = @"id001";
        NSMutableDictionary *collector = [NSMutableDictionary dictionary];
        [collector setObject:itemId forKey:@"userId"];
        [collector setObject:[NSString stringWithFormat:@"fname-%@", itemId] forKey:@"firstName"];
        [collector setObject:[NSString stringWithFormat:@"lname-%@", itemId] forKey:@"lastName"];
        [collector setObject:[NSString stringWithFormat:@"gender-%@", itemId] forKey:@"gender"];
        self.user = [NSMutableDictionary dictionaryWithDictionary:collector];
    }
    return self;
}

+ (HPSyncService *)sharedInstance {
    static dispatch_once_t onceToken;
    static HPSyncService *svc = nil;
    dispatch_once(&onceToken, ^{
        svc = [[HPSyncService alloc] init];
    });
    return svc;
}

- (void)fetchType:(NSString *)type userid:(NSString *)itemId completion:(void (^)(NSDictionary *))completion {
    NSLog(@"***** [HPSyncService] %s called", __PRETTY_FUNCTION__);

    if ([@"user" isEqualToString:type]) {

        if (!self.user[@"dateOfBirth"]) {
            NSCalendar *cal = [NSCalendar currentCalendar];
            NSDateComponents *components = [[NSDateComponents alloc] init];
            [components setYear:1980];
            [components setMonth:1];
            [components setDay:1];
            self.user[@"dateOfBirth"] = [cal dateFromComponents:components];
        }

        NSDictionary *data = [NSDictionary dictionaryWithDictionary:self.user];
        completion(data);
    } else {
        completion(nil);
    }
}

- (void)updateType:(NSString *)type completion:(void (^)(NSDictionary *))completion {

//    NSLog(@"***** [HPSyncService] %s called", __PRETTY_FUNCTION__);

    if ([@"user" isEqualToString:type]) {
        NSCalendar *cal = [NSCalendar currentCalendar];
        NSDateComponents *components = [[NSDateComponents alloc] init];
        [components setYear:2000];
        [components setMonth:1];
        [components setDay:1];
        self.user[@"dateOfBirth"] = [cal dateFromComponents:components];
        NSDictionary *data = [NSDictionary dictionaryWithDictionary:self.user];
        completion(data);
    } else {
        completion(nil);
    }
}

- (RACSignal *)loadType:(NSString *)type withId:(NSString *)userId {
    return nil;
}

- (RACSignal *)updateType:(NSString *)type withId:(NSString *)userId value:(HPUser *)user {
    return nil;
}

@end
